/*
 * @(#)MaintUpdateAlertAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.alert.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.alert.AlertOperationConstant;
import com.dcivision.alert.bean.MtmUpdateAlertRecipient;
import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.bean.UpdateAlertType;
import com.dcivision.alert.core.AlertManager;
import com.dcivision.alert.dao.UpdateAlertDAObject;
import com.dcivision.alert.dao.UpdateAlertTypeDAObject;
import com.dcivision.contact.bean.MtmContactListObjectLink;
import com.dcivision.contact.dao.MtmContactListObjectLinkDAObject;
import com.dcivision.dms.EmailAuditTrailConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsEmailAuditTrail;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.dao.DmsEmailAuditTrailDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.dao.InviteePickerHistoryDAObject;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
/**
  MaintUpdateAlertAction.java

  This class is for maint update alert action, the based one

    @author          Zoe Shum
    @company         DCIVision Limited
    @creation date   21/02/2004
    @version         $Revision: 1.27.2.1 $
*/

public class MaintUpdateAlertAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.27.2.1 $";


  public MaintUpdateAlertAction() {
    super();
  }

  /**
  * getMajorDAOClassName
  *
  * @return  The class name of the major DAObject will be used in this action.
  */
  public String getMajorDAOClassName() {
    return("com.dcivision.alert.dao.UpdateAlertDAObject");
  }

  /**
  * getFunctionCode
  *
  * @return  The corresponding system function code of action.
  */
  public String getFunctionCode() {
    return(null);
  }

  /**
   *  Method execute() - set request attributes and call super method
   *
   *  @param      mapping               ActionMapping from struts
   *  @param      form                  ActionForm from struts
   *  @param      request               HttpServletReuqest
   *  @param      respond               HttpServletRespond
   *  @return     ActionForward         Return the action forward object for struts
   *  @throws     ServletException      Throws ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    MaintUpdateAlertForm maintUpdateAlertForm = (MaintUpdateAlertForm) form;
    String opMode = maintUpdateAlertForm.getOpMode();
    String navMode = maintUpdateAlertForm.getNavMode();

    // Set function code if necessary.
    if (!Utility.isEmpty(maintUpdateAlertForm.getCurFunctionCode())) {
      this.setFunctionCode(maintUpdateAlertForm.getCurFunctionCode());
    }

    String alertType = maintUpdateAlertForm.getAlertType();
    log.debug("alertType = " + alertType);
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }

    if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
      // Insert operation.
      try {
        this.insertRecord(mapping, maintUpdateAlertForm, request, response);
        this.handleWorkflowRoutine(mapping, maintUpdateAlertForm, request, response, opMode, navMode);
        this.commit(request);
        addMessage(request, MESSAGE_RECORD_INSERT);
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      }
      if (isError(request)) {
        maintUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
        if (AlertOperationConstant.LIST_ALERT_SUMMARY.equals(navMode)){
          return mapping.findForward(navMode);
        }else{
          return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
        }
      } else {
        maintUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
        if (AlertOperationConstant.LIST_ALERT_SUMMARY.equals(navMode)){
          return mapping.findForward(navMode);
        }else{
          return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
        }
      }
    } else if (GlobalConstant.OP_MODE_UPDATE.equals(opMode)) {
      // Update operation.
      try {
        this.updateRecord(mapping, maintUpdateAlertForm, request, response);
        this.handleWorkflowRoutine(mapping, maintUpdateAlertForm, request, response, opMode, navMode);
        this.commit(request);
        addMessage(request, MESSAGE_RECORD_UPDATE);
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      }
      if (isError(request)) {
        maintUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
        if (AlertOperationConstant.LIST_ALERT_SUMMARY.equals(navMode)){
          return mapping.findForward(navMode);
        }else{
          return mapping.findForward(GlobalConstant.NAV_MODE_EDIT);
        }
      } else {
        maintUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
        if (AlertOperationConstant.LIST_ALERT_SUMMARY.equals(navMode)){
          return mapping.findForward(navMode);
        }else{
          return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
        }
      }
    } else if (GlobalConstant.OP_MODE_DELETE.equals(opMode)) {
      // Delete operation.
      try {
        this.deleteRecord(mapping, maintUpdateAlertForm, request, response);
        this.handleWorkflowRoutine(mapping, maintUpdateAlertForm, request, response, opMode, navMode);
        this.commit(request);
        addMessage(request, MESSAGE_RECORD_DELETE);
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      }
      if (isError(request)) {
        maintUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
        if (AlertOperationConstant.LIST_ALERT_SUMMARY.equals(navMode)){
          return mapping.findForward(navMode);
        }else{
          return mapping.findForward(GlobalConstant.NAV_MODE_EDIT);
        }
      } else {
        maintUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
        if (AlertOperationConstant.LIST_ALERT_SUMMARY.equals(navMode)){
          return mapping.findForward(navMode);
        }else{
          return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
        }
      }
    }
    else {
      return (super.execute(mapping, form, request, response));
    }
  }

  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer, conn);
    UpdateAlertTypeDAObject updateAlertTypeDAO = new UpdateAlertTypeDAObject(sessionContainer, conn);

    MaintUpdateAlertForm maintUpdateAlertForm = (MaintUpdateAlertForm)form;
   // maintDmsUpdateAlertForm=this.retrievalTargetObject(maintDmsUpdateAlertForm);
    List typeList = new ArrayList();
    log.debug("maintDmsUpdateAlertForm.getAlertType() = "+maintUpdateAlertForm.getAlertType());
    log.debug("maintDmsUpdateAlertForm.getID() = "+maintUpdateAlertForm.getID());

    UpdateAlert updateAlert = null;
    Integer inviteTypeID = null;
    if (UpdateAlert.INVITE_TYPE.equals(maintUpdateAlertForm.getAlertType())){
      updateAlert=(UpdateAlert)updateAlertDAO.getByObjectTypeObjectIDCreatorID(GlobalConstant.OBJECT_TYPE_DOCUMENT, new Integer(maintUpdateAlertForm.getObjectID()), sessionContainer.getUserRecordID(), UpdateAlert.INVITE_TYPE);
    }else{
      updateAlert=(UpdateAlert)updateAlertDAO.getByObjectTypeObjectIDCreatorID(GlobalConstant.OBJECT_TYPE_DOCUMENT, new Integer(maintUpdateAlertForm.getObjectID()), sessionContainer.getUserRecordID());
    }

    if (UpdateAlert.INVITE_TYPE.equals(maintUpdateAlertForm.getAlertType())){
      typeList = updateAlertTypeDAO.getByUpdateAlertIDByOwnerID(TextUtility.parseIntegerObj(maintUpdateAlertForm.getID()), UpdateAlert.INVITE_TYPE, sessionContainer.getUserRecordID());
    }else{
      typeList = updateAlertTypeDAO.getByUpdateAlertIDByOwnerID(TextUtility.parseIntegerObj(maintUpdateAlertForm.getID()), sessionContainer.getUserRecordID());
    }
    // set action type
    if (!Utility.isEmpty(typeList)){
      String[] actions = new String[typeList.size()];
      for (int i=0; i<typeList.size(); ++i) {
        UpdateAlertType alertType = (UpdateAlertType)typeList.get(i);
        actions[i]=alertType.getActionType();
        if (i==0){
          updateAlert.setDueDate(alertType.getDueDate());
          updateAlert.setMessage(alertType.getMessage());
          inviteTypeID = alertType.getID();
        }
      }
      maintUpdateAlertForm.setActionType(actions);
    }

    AlertManager alertManager = new AlertManager(sessionContainer, conn);
    // set notify way
    if (typeList!=null && typeList.size()>0) {
      String[] asNotifyWays = TextUtility.splitString( ((UpdateAlertType)typeList.get(0)).getNotifyWay(), UpdateAlert.SEPARATOR );
      maintUpdateAlertForm.setNotifyWay(asNotifyWays);
    }
    maintUpdateAlertForm.setFormData(updateAlert);
    maintUpdateAlertForm.setMessage(updateAlert.getMessage());

    //set Invite related info
    if (UpdateAlert.INVITE_TYPE.equals(maintUpdateAlertForm.getAlertType())){
      List userRecipientList = alertManager.getRecipientByUpdateAlertTypeID(inviteTypeID, UpdateAlert.USER_RECIPIENT);
      maintUpdateAlertForm.setUserList(Utility.getStringArray(userRecipientList));
      List groupRecipientList = alertManager.getRecipientByUpdateAlertTypeID(inviteTypeID, UpdateAlert.GROUP_RECIPIENT);
      maintUpdateAlertForm.setGroupList(Utility.getStringArray(groupRecipientList));
      List roleRecipientList = alertManager.getRecipientByUpdateAlertTypeID(inviteTypeID, UpdateAlert.ROLE_RECIPIENT);
      maintUpdateAlertForm.setRoleList(Utility.getStringArray(roleRecipientList));
    }

    conn = null;
    sessionContainer=null;
    updateAlertDAO=null;
    updateAlertTypeDAO=null;
    alertManager.release();

  }

  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {

    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    InviteePickerHistoryDAObject inviteePickerHistoryDAObject = new InviteePickerHistoryDAObject(sessionContainer,conn);
    MaintUpdateAlertForm maintUpdateAlertForm = (MaintUpdateAlertForm)form;
    String objectName = maintUpdateAlertForm.getObjectName();
    StringBuffer toAddress = new StringBuffer();
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DmsDocument document = docRetrievalManager.getDocument(TextUtility.parseIntegerObj(maintUpdateAlertForm.getID()));
    String locationPath = "";
    if(!Utility.isEmpty(document)){
      locationPath = docRetrievalManager.getLocationPath(document.getParentID())+"\\"+document.getDocumentName();
    }else{
    	locationPath = objectName;
    }
    String[] allUserList=maintUpdateAlertForm.getUserList();
    String[] allGroupList=maintUpdateAlertForm.getGroupList();
    String[] allRoleList=maintUpdateAlertForm.getRoleList();
    
    //Add By Jim Zhou     2006/11/29      EIP-90    for invitee picker history
    inviteePickerHistoryDAObject.updateInviteeHistory(allUserList,allGroupList,allRoleList,SystemFunctionConstant.DMS);
    //Add End
    
    //get additional contact list
    if(!Utility.isEmpty(maintUpdateAlertForm.getContactList())){
      allUserList=this.getUserGroupRoleList(allUserList,maintUpdateAlertForm.getContactList(),sessionContainer,conn,MtmContactListObjectLink.OBJECT_TYPE_USER_RECORD);
      allGroupList=this.getUserGroupRoleList(allGroupList,maintUpdateAlertForm.getContactList(),sessionContainer,conn,MtmContactListObjectLink.OBJECT_TYPE_USER_GROUP);
      allRoleList=this.getUserGroupRoleList(allRoleList,maintUpdateAlertForm.getContactList(),sessionContainer,conn,MtmContactListObjectLink.OBJECT_TYPE_USER_ROLE);
    }
        
    // insert record into UPDATE_ALERT
    UpdateAlert updateAlert = (UpdateAlert)maintUpdateAlertForm.getFormData();
    updateAlert.setMessage(maintUpdateAlertForm.getMessage());
    updateAlert.setAlertSubject(maintUpdateAlertForm.getAlertSubject());
    updateAlert.setObjectType(GlobalConstant.OBJECT_TYPE_DOCUMENT);
    updateAlert.setDueDate(maintUpdateAlertForm.parseTimestamp(maintUpdateAlertForm.getDueDate()));

    // insert record into UPDATE_ALERT_TYPE
    UpdateAlertType[] updateAlertTypes = new UpdateAlertType[maintUpdateAlertForm.getActionType().length];
    for (int i=0; i<maintUpdateAlertForm.getActionType().length; ++i) {
      String sNotify = "";
      for (int j=0; j<maintUpdateAlertForm.getNotifyWay().length; ++j) {
        sNotify += (maintUpdateAlertForm.getNotifyWay()[j] + UpdateAlert.SEPARATOR);
      }
      UpdateAlertType updateAlertType = new UpdateAlertType();
      updateAlertType.setUpdateAlertID(updateAlert.getID());
      updateAlertType.setActionType(maintUpdateAlertForm.getActionType()[i]);
      updateAlertType.setNotifyWay(sNotify);
      updateAlertType.setMessage(updateAlert.getMessage());
      updateAlertType.setAlertSubject(updateAlert.getAlertSubject());
      updateAlertType.setDueDate(updateAlert.getDueDate());
      updateAlertType.setNotifySelf(updateAlert.getNotifySelf());
      updateAlertTypes[i]=updateAlertType;
      ListUpdateAlertSummaryForm listForm=new ListUpdateAlertSummaryForm();
      listForm.setUpdateAlertTypeID(request.getParameter("updateAlertTypeID"));
      request.setAttribute("updateAlertTypeID",request.getParameter("updateAlertTypeID"));
    }

    AlertManager alertManager = new AlertManager(sessionContainer, conn);
    MtmUpdateAlertRecipient[] updateRecipient = new MtmUpdateAlertRecipient[1];
    // insert record into MTM_UPDATE_ALERT_RECIPIENT
    if (UpdateAlert.ALERT_TYPE.equals(maintUpdateAlertForm.getAlertType())){
      MtmUpdateAlertRecipient mtmUpdateAlertRecipient = new MtmUpdateAlertRecipient();
      mtmUpdateAlertRecipient.setRecipientType(GlobalConstant.SUBJECT_TYPE_USER);
      mtmUpdateAlertRecipient.setRecipientID(sessionContainer.getUserRecordID());
      updateRecipient[0]=mtmUpdateAlertRecipient;
      updateAlert = alertManager.createUpdateAlert(updateAlert, updateAlertTypes, null, updateRecipient);

      // update record in DMS_DOCUMENT
    //  docOperationManager.setAlertEditID(updateAlert.getObjectID(), updateAlert.getID());

    }else if (UpdateAlert.INVITE_TYPE.equals(maintUpdateAlertForm.getAlertType())){
      updateRecipient = alertManager.getRecipient(maintUpdateAlertForm.getUserList(), maintUpdateAlertForm.getGroupList(), maintUpdateAlertForm.getRoleList(), maintUpdateAlertForm.getContactList(),maintUpdateAlertForm.getContactPersonList());

      List notifyUserIDList = alertManager.getDistinctUserIDListByLists(allUserList, allGroupList, allRoleList);
      for (int i = 0; i < notifyUserIDList.size(); i++) {
        //Disable the notification to creatror
        Integer userID = (Integer)notifyUserIDList.get(i);
        String userEmail = UserInfoFactory.getUserEmailAddress(userID);
        if(!Utility.isEmpty(userEmail)){
        	toAddress.append(userEmail+" ; ");
        }
      }
      updateAlert =alertManager.createUpdateAlert(updateAlert, updateAlertTypes, updateRecipient, null, objectName, null, objectName, sessionContainer.getUserRecordID(), notifyUserIDList);

      // update record in DMS_DOCUMENT
  //    docOperationManager.setAlertInviteID(updateAlert.getObjectID(), updateAlert.getID());
    }
    maintUpdateAlertForm.setFormData(updateAlert);
    request.setAttribute("objectType", updateAlert.getObjectType());
    request.setAttribute("objectID", TextUtility.formatIntegerObj(updateAlert.getObjectID()));
    //request.setAttribute("actionType", updateAlert.get());
    request.setAttribute("updateAlertID", TextUtility.formatIntegerObj(updateAlert.getID()));
    request.setAttribute("actionType", maintUpdateAlertForm.getAlertType());
    if(UpdateAlert.INVITE_TYPE.equals(maintUpdateAlertForm.getAlertType())){
      try{
        // add Email Audit Trail Record;
        DmsEmailAuditTrail dmsEmailAuditTrail = new DmsEmailAuditTrail();
        DmsEmailAuditTrailDAObject emailDAO = new DmsEmailAuditTrailDAObject(sessionContainer,conn);
        dmsEmailAuditTrail.setUserid(sessionContainer.getUserRecordID());
        dmsEmailAuditTrail.setOperation(EmailAuditTrailConstant.OPERATION_EXTERNAL_DOCUMENT_INVITATION);
        dmsEmailAuditTrail.setEmailType(EmailAuditTrailConstant.EMAIL_TYPE_OUTBOUND);
        dmsEmailAuditTrail.setEmailFrom(UserInfoFactory.getUserEmailAddress(sessionContainer.getUserRecordID()).toString());
        if(!Utility.isEmpty(toAddress)){
          if(!Utility.isEmpty(maintUpdateAlertForm.getRecipients())){
            dmsEmailAuditTrail.setEmailTo(maintUpdateAlertForm.getRecipients().replaceAll(",",";")+";"+toAddress.toString().replaceAll(",",";"));
          }else{
            dmsEmailAuditTrail.setEmailTo(maintUpdateAlertForm.getRecipients().replaceAll(",",";")+toAddress.toString().replaceAll(",",";"));
          }
          
        }else{
          dmsEmailAuditTrail.setEmailTo(maintUpdateAlertForm.getRecipients().replaceAll(",",";"));
        }
        dmsEmailAuditTrail.setEmailCc(maintUpdateAlertForm.getCCRecipients().replaceAll(",",";"));
        dmsEmailAuditTrail.setEmailBcc(maintUpdateAlertForm.getBCCRecipients().replaceAll(",",";"));
        dmsEmailAuditTrail.setEmailSubject(maintUpdateAlertForm.getSubject());
        dmsEmailAuditTrail.setAttchSource("DMS");
        dmsEmailAuditTrail.setAttchName(locationPath);
        dmsEmailAuditTrail.setSentDate(Utility.getCurrentTimestamp().toString());
        dmsEmailAuditTrail.setAttchCount(new Integer(1));
        dmsEmailAuditTrail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
        dmsEmailAuditTrail.setCreatorID(sessionContainer.getUserRecordID());
        dmsEmailAuditTrail.setCreateDate(Utility.getCurrentTimestamp());
        dmsEmailAuditTrail.setUpdateCount(new Integer(0));
        dmsEmailAuditTrail.setUpdaterID(sessionContainer.getUserRecordID());
        dmsEmailAuditTrail.setUpdateDate(Utility.getCurrentTimestamp());
        dmsEmailAuditTrail = (DmsEmailAuditTrail)emailDAO.insertObject(dmsEmailAuditTrail);
        conn.commit();
      }catch(Exception e){
        log.error(e, e);
      }
    }
//    conn = null;
//    sessionContainer=null;
    alertManager.release();

  }

  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {

    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);

    MaintUpdateAlertForm maintUpdateAlertForm = (MaintUpdateAlertForm)form;
    String objectName = maintUpdateAlertForm.getObjectName();
    StringBuffer toAddress = new StringBuffer();
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DmsDocument document = docRetrievalManager.getDocument(TextUtility.parseIntegerObj(maintUpdateAlertForm.getID()));
    String locationPath = "";
    if(!Utility.isEmpty(document)){
    	locationPath = docRetrievalManager.getLocationPath(document.getParentID())+"\\"+document.getDocumentName();
    }else{
    	locationPath = objectName;
    }
    String[] allUserList=maintUpdateAlertForm.getUserList();
    String[] allGroupList=maintUpdateAlertForm.getGroupList();
    String[] allRoleList=maintUpdateAlertForm.getRoleList();
    //get additional contact list
    if(!Utility.isEmpty(maintUpdateAlertForm.getContactList())){
      allUserList=this.getUserGroupRoleList(allUserList,maintUpdateAlertForm.getContactList(),sessionContainer,conn,MtmContactListObjectLink.OBJECT_TYPE_USER_RECORD);
      allGroupList=this.getUserGroupRoleList(allGroupList,maintUpdateAlertForm.getContactList(),sessionContainer,conn,MtmContactListObjectLink.OBJECT_TYPE_USER_GROUP);
      allRoleList=this.getUserGroupRoleList(allRoleList,maintUpdateAlertForm.getContactList(),sessionContainer,conn,MtmContactListObjectLink.OBJECT_TYPE_USER_ROLE);
    }

    // update record in UPDATE_ALERT
    UpdateAlert updateAlert = (UpdateAlert)maintUpdateAlertForm.getFormData();
    updateAlert.setMessage(maintUpdateAlertForm.getMessage());
    updateAlert.setAlertSubject(maintUpdateAlertForm.getAlertSubject());
    updateAlert.setDueDate(maintUpdateAlertForm.parseTimestamp(maintUpdateAlertForm.getDueDate()));
    updateAlert.setAlertType(maintUpdateAlertForm.getAlertType());
    updateAlert.setClearLogs(maintUpdateAlertForm.getClearLogs());

    // insert record into UPDATE_ALERT_TYPE
    UpdateAlertType[] updateAlertTypes = new UpdateAlertType[maintUpdateAlertForm.getActionType().length];
    for (int i=0; i<maintUpdateAlertForm.getActionType().length; ++i) {
      String sNotify = "";
      for (int j=0; j<maintUpdateAlertForm.getNotifyWay().length; ++j) {
        sNotify += (maintUpdateAlertForm.getNotifyWay()[j] + UpdateAlert.SEPARATOR);
      }
      UpdateAlertType updateAlertType = new UpdateAlertType();
      updateAlertType.setUpdateAlertID(updateAlert.getID());
      updateAlertType.setActionType(maintUpdateAlertForm.getActionType()[i]);
      updateAlertType.setNotifyWay(sNotify);
      updateAlertType.setMessage(updateAlert.getMessage());
      updateAlertType.setAlertSubject(updateAlert.getAlertSubject());
      updateAlertType.setDueDate(updateAlert.getDueDate());
      updateAlertType.setNotifySelf(updateAlert.getNotifySelf());      
      updateAlertTypes[i]=updateAlertType;
      //updateAlertType = (UpdateAlertType)updateAlertTypeDAO.insertObject(updateAlertType);
    }

      AlertManager alertManager = new AlertManager(sessionContainer, conn);
      MtmUpdateAlertRecipient[] updateRecipient = new MtmUpdateAlertRecipient[1];
    // insert record into MTM_UPDATE_ALERT_RECIPIENT
    if (UpdateAlert.ALERT_TYPE.equals(maintUpdateAlertForm.getAlertType())){
      MtmUpdateAlertRecipient mtmUpdateAlertRecipient = new MtmUpdateAlertRecipient();
      mtmUpdateAlertRecipient.setRecipientType(GlobalConstant.SUBJECT_TYPE_USER);
      mtmUpdateAlertRecipient.setRecipientID(sessionContainer.getUserRecordID());
      updateRecipient[0]=mtmUpdateAlertRecipient;
      //mtmUpdateAlertRecipientDAO.insertObject(mtmUpdateAlertRecipient);
      updateAlert = alertManager.updateUpdateAlert(updateAlert, updateAlertTypes, null, updateRecipient);

    }else if (UpdateAlert.INVITE_TYPE.equals(maintUpdateAlertForm.getAlertType())){
      updateRecipient = alertManager.getRecipient(maintUpdateAlertForm.getUserList(), maintUpdateAlertForm.getGroupList(), maintUpdateAlertForm.getRoleList(),maintUpdateAlertForm.getContactList(),maintUpdateAlertForm.getContactPersonList());
      List notifyUserIDList = alertManager.getDistinctUserIDListByLists(allUserList, allGroupList, allRoleList);
      for (int i = 0; i < notifyUserIDList.size(); i++) {
        //Disable the notification to creatror
        Integer userID = (Integer)notifyUserIDList.get(i);
        String userEmail = UserInfoFactory.getUserEmailAddress(userID);
        if(!Utility.isEmpty(userEmail)){
        	toAddress.append(userEmail+" ; ");
        }
      }
      updateAlert =alertManager.updateUpdateAlert(updateAlert, updateAlertTypes, updateRecipient, null, objectName, null, objectName, sessionContainer.getUserRecordID(), notifyUserIDList);
    }
    //maintDmsUpdateAlertForm.setFormData(updateAlert);
    maintUpdateAlertForm.setFormData(updateAlert);
    request.setAttribute("objectType", updateAlert.getObjectType());
    request.setAttribute("objectID", TextUtility.formatIntegerObj(updateAlert.getObjectID()));
//request.setAttribute("actionType", updateAlert.get());
    request.setAttribute("updateAlertID", TextUtility.formatIntegerObj(updateAlert.getID()));
    request.setAttribute("actionType", maintUpdateAlertForm.getAlertType());
    if(UpdateAlert.INVITE_TYPE.equals(maintUpdateAlertForm.getAlertType())){
      try{
       // add Email Audit Trail Record;
        DmsEmailAuditTrail dmsEmailAuditTrail = new DmsEmailAuditTrail();
        DmsEmailAuditTrailDAObject emailDAO = new DmsEmailAuditTrailDAObject(sessionContainer,conn);
        dmsEmailAuditTrail.setUserid(sessionContainer.getUserRecordID());
        dmsEmailAuditTrail.setOperation(EmailAuditTrailConstant.OPERATION_EXTERNAL_DOCUMENT_INVITATION);
        dmsEmailAuditTrail.setEmailType(EmailAuditTrailConstant.EMAIL_TYPE_OUTBOUND);
        dmsEmailAuditTrail.setEmailFrom(UserInfoFactory.getUserEmailAddress(sessionContainer.getUserRecordID()).toString());
        if(!Utility.isEmpty(toAddress)){
         if(!Utility.isEmpty(maintUpdateAlertForm.getRecipients())){
           dmsEmailAuditTrail.setEmailTo(maintUpdateAlertForm.getRecipients().replaceAll(",",";")+";"+toAddress.toString().replaceAll(",",";"));
         }else{
           dmsEmailAuditTrail.setEmailTo(maintUpdateAlertForm.getRecipients().replaceAll(",",";")+toAddress.toString().replaceAll(",",";"));
         }
         
        }else{
         dmsEmailAuditTrail.setEmailTo(maintUpdateAlertForm.getRecipients().replaceAll(",",";"));
        }
        dmsEmailAuditTrail.setEmailCc(maintUpdateAlertForm.getCCRecipients().replaceAll(",",";"));
        dmsEmailAuditTrail.setEmailBcc(maintUpdateAlertForm.getBCCRecipients().replaceAll(",",";"));
        dmsEmailAuditTrail.setEmailSubject(maintUpdateAlertForm.getSubject());
        dmsEmailAuditTrail.setAttchSource("DMS");
        dmsEmailAuditTrail.setAttchName(locationPath);
        dmsEmailAuditTrail.setSentDate(Utility.getCurrentTimestamp().toString());
        dmsEmailAuditTrail.setAttchCount(new Integer(1));
        dmsEmailAuditTrail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
       dmsEmailAuditTrail.setCreatorID(sessionContainer.getUserRecordID());
       dmsEmailAuditTrail.setCreateDate(Utility.getCurrentTimestamp());
       dmsEmailAuditTrail.setUpdateCount(new Integer(0));
       dmsEmailAuditTrail.setUpdaterID(sessionContainer.getUserRecordID());
       dmsEmailAuditTrail.setUpdateDate(Utility.getCurrentTimestamp());
        dmsEmailAuditTrail = (DmsEmailAuditTrail)emailDAO.insertObject(dmsEmailAuditTrail);
        conn.commit();
      }catch(Exception e){
        log.error(e, e);
      }
    }
//    conn = null;
//    sessionContainer=null;
    alertManager.release();

  }

  public void deleteRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {

    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);

    MaintUpdateAlertForm maintUpdateAlertForm = (MaintUpdateAlertForm)form;
    UpdateAlert updateAlert = (UpdateAlert) maintUpdateAlertForm.getFormData();
    updateAlert.setAlertType(maintUpdateAlertForm.getAlertType());
    updateAlert.setClearLogs(maintUpdateAlertForm.getClearLogs()); //EIP-1174 07/01/10 LEE
    Integer objectID = new Integer(maintUpdateAlertForm.getObjectID());

    // hard delete the records
    AlertManager alertManager = new AlertManager(sessionContainer, conn);
    alertManager.deleteUpdateAlert(updateAlert);

    conn = null;
    sessionContainer=null;
    alertManager.release();
  }
  
  /**
   * for haveing additional contacts,need get all user,group,role.
   * @param maintUpdateAlertForm
   * @param sessionContainer
   * @param conn
   * @param type
   * @return String[]
   * @throws ApplicationException
   */
  protected String[] getUserGroupRoleList(String[] generalContact,String[] contactList,SessionContainer sessionContainer,Connection conn,String type) throws ApplicationException{
  	MtmContactListObjectLinkDAObject mtmContactListObjectLinkDAO=new MtmContactListObjectLinkDAObject(sessionContainer,conn);
  	List resultList=new ArrayList();
  	String[] result=null;
  	for(int i=0;i<contactList.length;i++){
      Integer contactListID=TextUtility.parseIntegerObj(contactList[i]); 
      List list=mtmContactListObjectLinkDAO.getObjectIDListByObjectTypeContactListID(type,contactListID);
      //if(MtmContactListObjectLink.OBJECT_TYPE_USER_RECORD.equals(type)){
    	List newUserList=new ArrayList();
        for(int j=0;j<list.size();j++){
          Integer userRecordID=(Integer)list.get(j);
          newUserList.add(userRecordID.toString());
        }
        list=newUserList;
     // }
      if(!Utility.isEmpty(generalContact)){  
        for(int k=0;k<generalContact.length;k++){
          if(list.contains(generalContact[k])){
            list.remove(generalContact[k]);
          }
        }
      }
      resultList.addAll(list);        
    }
  	java.util.Hashtable hst=new java.util.Hashtable();
    for(int m=0;m<resultList.size();m++){
      String userID=(String)resultList.get(m);
      hst.put(userID,userID);
    }
    if(hst.size()>0){
      java.util.Enumeration e = hst.elements();
      int j = 0;
      resultList.add(0,e.nextElement());
      while (e.hasMoreElements()) {
        j++;
        resultList.add(j,e.nextElement());
      }
    }
    if(resultList.size()>0){
      if(!Utility.isEmpty(generalContact)){
        result=new String[resultList.size()+generalContact.length];
      }else{
      	result=new String[resultList.size()];
      }
      for(int i=0;i<resultList.size();i++){
        result[i]=(String)resultList.get(i);
      }
      if(!Utility.isEmpty(generalContact)){
        for(int j=0;j<generalContact.length;j++){
      	  result[resultList.size()+j]=generalContact[j];
        }
      }
      return result;
    }else{
      return generalContact;
    }   
  }  
  
}
